﻿using System;
using System.IO.IsolatedStorage;

namespace mal.WP7.GoogleAnalytics.Business.Repository
{
    public class CachedObject<T>
    {
        #region Fields
        private DateTime creationDate;
        private T value;
        #endregion

        #region Construction / Destruction
        public CachedObject()
        {
            this.creationDate = DateTime.Now;
        }
        #endregion

        #region enum, struct, class

        #endregion

        #region Properties
        public DateTime CreationDate
        {
            get { return this.creationDate; }

            set { this.creationDate = value; }
        }

        public T Value
        {
            get { return this.value; }

            set { this.value = value; }
        }
        #endregion

        #region methods

        #endregion
    }

    public class CachedObjectManager
    {
        public static T GetCachedObject<T>(string key)
        {

            if (IsolatedStorageSettings.ApplicationSettings.Contains(key))
            {
                try
                {
                    CachedObject<T> result = (CachedObject<T>)IsolatedStorageSettings.ApplicationSettings[key];

                    int cacheDuration = 3600 * 4;
#if MOKE || DEBUG
                    cacheDuration = 10;
#endif

                    if (DateTime.Now.Subtract(result.CreationDate).TotalSeconds < cacheDuration)
                    {
                        return result.Value;
                    }
                }
                catch (Exception e)
                {
                    Console.Write(e.Message);
                }
            }

            return default(T);
        }

        public static object cachedLock = new object();

        public static void InsertCachedObject<T>(T value, string key)
        {
            lock (cachedLock)
            {
                if (IsolatedStorageSettings.ApplicationSettings.Contains(key))
                {
                    IsolatedStorageSettings.ApplicationSettings.Remove(key);
                    IsolatedStorageSettings.ApplicationSettings.Save();
                }

                CachedObject<T> result = new CachedObject<T>();
                result.Value = value;

                IsolatedStorageSettings.ApplicationSettings[key] = result;
                IsolatedStorageSettings.ApplicationSettings.Save();
            }
        }
    }
}
